<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\api\controller;

use app\common\model\AppAccountLog;

use app\common\model\BetsLog;

use app\common\model\BonusLog;
use app\common\model\ChainDailyStatistics;
use app\common\model\CoinAddress;
use app\common\model\CompanyAccount;

use app\common\model\GamblerKingInvestment;
use app\common\model\GamblerKingInvestmentUser;
use app\common\model\GamesLog;

use app\common\model\LoginLog;
use app\common\model\Lottery;
use app\common\model\LotteryPlay;
use app\common\model\LotteryRound;
use app\common\model\Member;
use app\common\model\OtcFeedback;

use app\common\model\OtcOrder;
use app\common\model\OtcShop;

use app\common\model\Picture;
use app\common\model\PlanNumber;
use app\common\model\PlanUserProgramme;
use app\common\model\ShopPoundageLog;
use app\common\model\UserBadRecord;
use app\common\model\UserKingInvestment;
use app\common\model\UserLevel;
use app\common\model\UserLevelLog;
use app\common\model\UserSms;
use app\common\model\WalletPrice;
use app\common\model\CompanyAccountLog;
use QL\QueryList;

use think\Controller;
use think\Db;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;

class Autoapi extends Controller
{
    //采集充值订单
    public function auto_collect_recharge_order()
    {
        $orders = Db::name("recharge_auto")->where(["status" => 0])->select();


        foreach ($orders as $k => $v) {

            $wallet = Db::name("wallet")->where(["id" => $v["wallet_id"]])->find();
            $res = coin_collect_order($wallet['symbol'], $v['address'], $v['wallet_id']);
//            dd($res);
            if (empty($res)) {
                if ($v['collect_count'] > 4) {
                    Db::name("recharge_auto")->where(['id' => $v['id']])->update(['status' => 2]);
                } else {
                    Db::name("recharge_auto")->where(['id' => $v['id']])->setInc('collect_count');
                }
            } else {
                Db::name("recharge_auto")->where(['id' => $v['id']])->update(['status' => 1, 'collect_time' => time()]);
                Db::name("recharge_auto")->where(['id' => $v['id']])->setInc('collect_count');
                foreach ($res as $key => $value) {
                    //判断该订单是否已有
                    $count = Db::name("transfer")->where("serial_number", $value["tx"])->count();
//                     d($count);
                    if ($count) {
                        continue;
                    }

                    //充值订单
                    $data['form_wallet_id'] = $v["wallet_id"];
                    $data['user_id'] = $v["user_id"];
                    $data['type'] = 10;
                    $data['from'] = $value["from"];
                    $data['to'] = $value["to"];
                    $data['txFee'] = $value["txFee"];
                    $data['hash'] = $value["tx"];
                    $data['number'] = $value["number"];
                    $data['money'] = $value["money"];
                    $data['create_time'] = time();
                    $data['update_time'] = time();
                    $data['state'] = 0;
                    $data['is_coin'] = 1;
                    $data['serial_number'] = $value["tx"];
                    $datas[] = $data;
                }
                if (!empty($datas)) {
                    Db::name("transfer")->insertAll($datas);

                }

            }


        }
    }


    //倒计时结束订单加入采集表
    public function auto_add_collect_order()
    {
        $orders = Db::name("recharge_address")->where(["status" => 0])->select();
        foreach ($orders as $k => $v) {
            if ($v["wallet_id"] == 6 || $v["wallet_id"] == 8) {
                $waiting_time = 300;
            } else {
                $waiting_time = 600;
            }
            if ($v["create_time"] < time() - $waiting_time) {
                $data = array(
                    "wallet_id" => $v["wallet_id"],
                    "user_id" => $v["user_id"],
                    "address_id" => $v["id"],
                    "create_time" => time(),
                    "update_time" => time(),
                    'address' => $v['address']
                );
                $res1 = Db::name("recharge_auto")->insert($data);
                $res2 = Db::name("recharge_address")->where(["id" => $v["id"]])->update(["status" => 1]);
                if (!$res1 || !$res2) {
                    dump("处理失败");
                    exit;
                }
            }

        }
    }

    //自动审核充值订单
    public function auto_examine_recharge_order()
    {
        $count = 0;

        #取出未进行加扣钱的用户订单记录
        $list = Db::name("transfer")->where("state = 0 and is_coin = 1 and type = 10")->order("id asc")->limit(5)->select();
        // $list = Db::name("transfer")->where("state = 0 and is_coin = 1 and type = 10")->where("last_time < ".(time()-120))->order("id asc")->limit(5)->select();
        //   dump($list);exit;
        $id_text = "";
        $wallet = \app\common\model\Wallet::where(['is_virtual' => 1, 'is_currency' => 1])->column('symbol', 'id');

        foreach ($list as $value) {

            Db::startTrans();
            try {

                if ($value['examine_count'] >= 120) {
                    //已经执行过三次审核，修改为失败，请人工审核
                    Db::name("transfer")->where("id", $value['id'])->update(['state' => 2, "update_time" => time()]);

                } else {
                    $mid = $value['form_wallet_id'];
//					dump($mid);
                    //判断该笔订单是否成功
                    $symbol = $wallet[$mid];
                    $tx = $value['hash'];
                    $userid = $value['user_id'];
                    $number = $value['number'];
//					dump($symbol);

                    if (query_tx_status($symbol, $tx, $mid) == 1) {
                        $account = Db::name("user_account")->where("user_id", $userid)->where("wallet_id", $mid)->find();
                        $member = Member::get($userid);

                        if ($member->mobile) {
                            //发消息
                            $code = $number;
                            $code1 = $wallet[$mid];
                            $lang = in_array($member['area'], ['86', '852', '853', '886']) ? 'zh-hk' : 'en-us';
                            $content = getConfig('otc_success_notice_' . $lang);
                            $content = str_replace('{$code}', $code, $content);
                            $content = str_replace('{$code1}', $code1, $content);

                            $data = [
                                'mobile' => $member->mobile,
                                'content' => $content,
                                'create_time' => TIME_NOW,
                                'sms_type' => 3,
                                'type' => 0,
                                'area' => $member->area
                            ];
                            $sms = UserSms::create($data);

                            if (getConfig('sms_is_test') != 1) {
                                $state = send_sms($member->mobile, $content, config('settings'), $member->area);
                                if ($state) {
                                    UserSms::where(['id' => $sms->id])->update(['state' => 2]);
                                }
                            }


                        }

                        //订单交易成功
                        //执行充值到账操作
                        //修改订单状态为完成
                        Db::name("transfer")->where("id", $value['id'])->update(['state' => 1, "update_time" => time()]);

                        //增加总数 和 可用
                        //按照比例增加
//						$number = $number * (float)$com_sys_config['finance_usdt_to_usd']; //在插入订单的时候已经按比例增加
                        Db::name("user_account")->where("user_id", $userid)->where("wallet_id", $mid)->setInc("balance", $number);
                        Db::name("user_account")->where("user_id", $userid)->where("wallet_id", $mid)->setInc("number", $number);

                        //写入资金流水
                        $accountlog['user_id'] = $userid;
                        $accountlog['number'] = $number;
                        $accountlog['wallet_id'] = $mid;
                        $accountlog['before_blance'] = $account['balance'];
                        $accountlog['after_blance'] = $account['balance'] + $number;
                        $accountlog['is_add'] = 1;
                        $accountlog['type'] = 21;
                        $accountlog['create_time'] = time();
                        $accountlog['serial_number'] = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                        Db::name("user_account_log")->insert($accountlog);
                        //写入排行榜记录
                        // UserRankingData::create([
                        //     'user_id'=>$userid,
                        //     'type'=>1,
                        //     'is_user'=>1,
                        //     'money'=>$number*$wallet['parities'],
                        //     'remark'=>'链上充值'.$wallet['name'].$number
                        // ]);


                    } else {
                        //订单未成功或者订单错误
                        //查询数自增1
                        //查询时间更新为当前时间
                        Db::name("transfer")->where("id", $value['id'])->setInc("examine_count");
                        Db::name("transfer")->where("id", $value['id'])->update(["last_time" => time()]);
                    }

                }

                // 提交事务
                Db::commit();

                $count++;
                $id_text .= $value['id'] . ",";
            } catch (\Exception $e) {
                dump($e->getMessage());
                // 回滚事务
                Db::rollback();

            }
        }


        $auto['title'] = "充值自动到账";//
        $auto['vcontent'] = "本次共执行" . $count . "次,id:" . $id_text;//
        $auto['add_time'] = time();//

        dump($auto);
    }

    //每日0点模板数据
    public function auto_online_transfer()
    {
        $content = Db::name("template")->where(["type" => 4, "status" => 1])->find()["content"];
        $content_arr = json_decode($content, true);
        dump($content_arr);
        exit;
        $ccie = Db::name("wallet")->where(["symbol" => "ccie"])->find();
        $eth = Db::name("wallet")->where(["symbol" => "eth"])->find();
        $get_token = $this->get_token();
        $url = COIN_URL . "/api/v1/transfer/add";
        foreach ($content_arr as $k => $v) {
            Db::startTrans();
            try {
                if ($v["flag"] == 1) {
                    $from_address = $ccie["ccie_bet_address"];
                } else {
                    $from_address = $ccie["ccie_reward_address"];
                };
                foreach ($v["address"] as $key => $value) {
                    $post_data = array(
                        "code" => "ETH/" . strtoupper($ccie['symbol']),
                        "from_address" => $from_address,
                        "to_address" => $value,
                        "number" => $v["amount"],
                        "password" => $eth["wallet_password"],
                        "nonce_str" => rand(1000, 9999)
                    );
                    $sign = md5(asc_sort($post_data) . '&key=' . "79ba9e912e708a0a3177df0641be1e5a");
                    $post_data['sign'] = $sign;
                    $result = json_decode(mycurl($url, $post_data, 1), true);
                    if (!empty($result['status']) && $result['status'] == 1) {
                        $transfer = array(
                            "from" => $post_data["from_address"],
                            "to" => $post_data["to_address"],
                            "amount" => $post_data["number"],
                            "create_time" => time(),
                            "update_time" => time(),
                            'haxi' => $result['data'],
                        );
                        Db::name("online_transfer")->insert($transfer);
                    } else {
                        if ($result['msg'] == 'insufficient funds for gas * price + value') {
                            $msg = lang("钱包余额不足");
                        } else {
                            $msg = $result['msg'];
                        }
                        $this->error($result['msg']);
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();

            }
        }
    }

//自动审核提现订单是否成功
    public function auto_examine_propose_order()
    {
        $count = 0;

        //查出已审核,未到账的订单
        $result = Db::name("transfer")->where("state = 3 and type = 20")->where("last_time < " . (time() - 120))->order("id asc")->limit(3)->select();
//		dump($result);
        $wallet = \app\common\model\Wallet::where(['is_virtual' => 1, 'is_currency' => 1])->column('symbol', 'id');
        $id_text = "";
        foreach ($result as $value) {
            Db::startTrans();
            try {
                $tx = $value['hash'];
                $mid = $value['to_wallet_id'];
                $userid = $value['user_id'];
                $number = $value['coin_number'];
                $symbol = Db::name("wallet")->where("id", $mid)->value("symbol");
                $account = Db::name("user_account")->where("user_id", $userid)->where("wallet_id", $mid)->lock(true)->find();
                if ($value['examine_count'] >= 60) {
                    //已经执行过三次审核，修改为失败，请人工审核
                    Db::name("transfer")->where("id", $value['id'])->update(['state' => 2, "update_time" => time()]);
                    //失败,增加可用
                    Db::name("user_account")->where("user_id", $userid)->where("wallet_id", $mid)->setInc("balance", $value['number']);
                    Db::name("user_account")->where("user_id", $userid)->where("wallet_id", $mid)->setDec("freeze_balance", $value['number']);


                    /*
                  //写入资金流水
                  $accountlog['user_id'] = $userid;
                  $accountlog['number'] = $value['number'];
                  $accountlog['wallet_id'] = $mid;
                  $accountlog['before_blance'] = $account['balance']-$value['number'];
                  $accountlog['after_blance'] = $account['balance'];
                  $accountlog['is_add'] = 1;
                  $accountlog['type'] = 9;
                  $accountlog['create_time'] = time();
                  $accountlog['serial_number'] = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                  Db::name("user_account_log")->insert($accountlog);
                  */
                } else {
                    if (query_tx_status($symbol, $tx, $mid) == 1) {
                        //成功,只改状态
                        Db::name("transfer")->where("id", $value['id'])->update(['state' => 1, "update_time" => time()]);

                        $wallet_address = '*****' . substr($value['to'], -4);
                        $member = Member::get($userid);
                        if ($member->mobile) {
                            //发消息
                            $code = $value['number'];
                            $code1 = $wallet[$mid];
                            $code2 = $wallet_address;
                            $lang = in_array($member['area'], ['86', '852', '853', '886']) ? 'zh-hk' : 'en-us';
                            $content = getConfig('otc_withdrwal_' . $lang);
                            $content = str_replace('{$code}', $code, $content);
                            $content = str_replace('{$code1}', $code1, $content);
                            $content = str_replace('{$code2}', $code2, $content);
                            $data = [
                                'mobile' => $member->mobile,
                                'content' => $content,
                                'create_time' => TIME_NOW,
                                'sms_type' => 5,
                                'type' => 0,
                                'area' => $member->area
                            ];
                            $sms = UserSms::create($data);

                            if (getConfig('sms_is_test') != 1) {
                                $state = send_sms($member->mobile, $content, config('settings'), $member->area);
                                if ($state) {
                                    UserSms::where(['id' => $sms->id])->update(['state' => 2]);
                                }
                            }

                        }
                    } else {
                        //订单未成功或者订单错误
                        //查询数自增1
                        //查询时间更新为当前时间
                        Db::name("transfer")->where("id", $value['id'])->setInc("examine_count");
                        Db::name("transfer")->where("id", $value['id'])->update(["last_time" => time()]);
                    }
                }

                // 提交事务
                Db::commit();

                $count++;
                $id_text .= $value['id'] . ",";
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
        }

        $auto['title'] = "提现订单是否成功";//
        $auto['vcontent'] = "本次共执行" . $count . "次,id:" . $id_text;//
        $auto['add_time'] = time();//

        dump($auto);
    }

    //交易记录
    public function coin_trade_log($mid, $address)
    {

        $money = Db::name("wallet")->where("id", $mid)->find();
        $rpc_host = $money['rpc_host'];

        switch ($money['symbol']) {
            case "BTC":
                $url = $rpc_host . "/index/usdt/getaccount?address=" . $address;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
                $result_label = curl_exec($ch);
                curl_close($ch);
                if (empty($result_label)) {
                    //没有标签
                    return -1;
                }
                $url = $rpc_host . "/index/usdt/listtransactions?account=" . $result_label;
                break;
            case "USDT":
                $url = $rpc_host . "/index/usdt/omni_listtransactions?address=" . $address;
                break;
            default:
                //其他币未对接
                return 0;
                break;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
        if (!empty($result)) {
            //基于BTC/USDT
//			dump($result);
            return json_decode($result, true);
        } else {
            //网络错误
            return -2;
        }
    }

    //自动更新BTC,USDT,ETH价格
    public function auto_update_coin_price()
    {
//		$url = "https://data.gateio.co/api2/1/tickers";
        //USDT
        $url = "http://47.75.203.208:19103/api2/1/ticker/usdt_cnyx";
        $prices = [];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
//        $result='{"result":"true","last":"7.067","lowestAsk":"7.079","highestBid":"7.067","percentChange":"0.21","baseVolume":"455095.71202748","quoteVolume":"64352.75049732","high24hr":"7.091","low24hr":"7.051"}';
        if (!empty($result)) {
            $result = json_decode($result, true);
            if (!empty($result['last']) && $result['last'] > 0) {
                cache('usdt', $result['last']);
                Db::name("wallet")->where("symbol = 'usdt'")->update(["update_time" => time(), "parities" => $result['last'], 'usdt_price' => 1]);
                Db::name("wallet")->where("symbol = '$'")->update(["update_time" => time(), "parities" => $result['last'], 'usdt_price' => 1]);
                $price = [
                    'symbol' => 'usdt',
                    'wallet_id' => 8,
                    'price' => $result['last'],
                    'create_time' => TIME_NOW,
                ];
                $prices[] = $price;

                cache('usdt', $result['last']);
            }
            dump($result['last']);
        }
        //BTC
        $url = "http://47.75.203.208:19103/api2/1/ticker/btc_cnyx";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
//        $result='{"quoteVolume":"1.2246152584","baseVolume":"67460.705384816254","highestBid":"55575.33","high24hr":"56177.76","last":"55685.32","lowestAsk":"55716.95","elapsed":"6ms","result":"true","low24hr":"53284.57","percentChange":"4.12"}';
        $result = json_decode($result, true);
        if (!empty($result['last']) && $result['last'] > 0) {
            Db::name("wallet")->where("symbol = 'btc'")->update(["update_time" => time(), "parities" => $result['last'], 'usdt_price' => ($result['last'] / cache('usdt'))]);
        }
        $price = [
            'symbol' => 'btc',
            'wallet_id' => 7,
            'price' => $result['last'],
            'create_time' => TIME_NOW,
        ];
        $prices[] = $price;
        dump($result['last']);

        //ETH
        $url = "http://47.75.203.208:19103/api2/1/ticker/eth_cnyx";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 开启使用SSL
        $result = curl_exec($ch);
        curl_close($ch);
//        $result='{"quoteVolume":"72.02422584","baseVolume":"75649.9682853425","highestBid":"1052.84","high24hr":"1058","last":"1054.26","lowestAsk":"1056.47","elapsed":"5ms","result":"true","low24hr":"1040.88","percentChange":"0.4"}';
        if (!empty($result)) {
            $result = json_decode($result, true);
            if (!empty($result['last']) && $result['last'] > 0) {
                Db::name("wallet")->where("symbol = 'eth'")->update(["update_time" => time(), "parities" => $result['last'], 'usdt_price' => ($result['last'] / cache('usdt'))]);
            }
            $price = [
                'symbol' => 'eth',
                'wallet_id' => 6,
                'price' => $result['last'],
                'create_time' => TIME_NOW,
            ];
            $prices[] = $price;
            dump($result['last']);
        }
        WalletPrice::insertall($prices);
    }

    //生成二维码接口
    public function png()
    {
        vendor("phpqrcode.phpqrcode");
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 10;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        //$path = "images/";
        // 生成的文件名
        //$fileName = $path.$size.'.png';
        ob_end_clean();
        \QRcode::png(input("text"), false, $level, $size, 1);
    }


    //采集金色财经快讯
    public function test()
    {

        $html = file_get_contents('https://api.jinse.com/v4/live/list?limit=20&reading=false&source=web&sort=&flag=down&id=0');
        $data = json_decode($html, true);
        $list = $data['list'][0]['lives'];
        $ars = [];
        foreach ($list as $k => $v) {
            $arr = explode('】', $v['content']);
            $content = $arr[1];
            $title = str_replace('【', '', $arr[0]);
            $info = \app\common\model\Article::where(['name' => $title])->find();
            if ($info) {
                break;
            }
            $ar = [
                'name' => $title,
                'content' => $content,
                'create_time' => TIME_NOW,
                'category_id' => 1,
                'source' => '金色财经',
                'member_id' => 1,
                'is_collect' => 1
            ];
            $ars[] = $ar;


        }
        \app\common\model\Article::insertall($ars);


    }


    //采集金色财经资讯
    public function test1()
    {
        include_once(ROOT_PATH . 'extend/QueryList/phpQuery.php');
        include_once(ROOT_PATH . 'extend/QueryList/QueryList.php');
        $html = file_get_contents('https://www.jinse.com/columns');
        $rules = array(
            //采集id为one这个元素里面的纯文本内容
            'title' => array('.js-title', 'title'),
            //采集class为two下面的超链接的链接
            'link' => array('.js-title', 'href'),
            //采集class为two下面的第二张图片的链接
            'img' => array('.js-single__left>img', 'src'),
            //采集span标签中的HTML内容
            'other' => array('.js-single__des', 'text')
        );

        $data = QueryList::Query($html, $rules)->data;

//        dd($data);
        $ars = [];
        foreach ($data as $k => $v) {
            if (!$v['link']) {
                continue;
            }
            $arr = explode('/', $v['link']);
            $arrs = explode('.', $arr[4]);
            $article_id = $arrs[0];
            if ($article_id == 'blockchain') {
                $arrs = explode('.', $arr[5]);
                $article_id = $arrs[0];
            }
            $info = Db::name('collect_article')->where(['article_id' => $article_id, 'source' => 1])->find();
            if ($info) {
                break;
            }
            $ar = [
                'title' => $v['title'],
                'source' => 1,
                'create_time' => TIME_NOW,
                'img' => $v['img'],
                'describe' => $v['other'],
                'url' => $v['link'],
                'article_id' => $article_id,
            ];
            $ars[] = $ar;


        }
        Db::name('collect_article')->insertall($ars);


    }

    //采集金色财经资讯内容
    public function test2()
    {
        include_once(ROOT_PATH . 'extend/QueryList/phpQuery.php');
        include_once(ROOT_PATH . 'extend/QueryList/QueryList.php');

        $list = Db::name('collect_article')->where(['status' => 1])->select();
        foreach ($list as $k => $v) {

            $html = file_get_contents($v['url']);

            $rules = array(
                //采集id为one这个元素里面的纯文本内容
                'content' => array('.js-article', 'html'),
            );

            $data = QueryList::Query($html, $rules)->data;
//            dd($html);
            if (empty($data)) {
                Db::name('collect_article')->where(['id' => $v['id']])->update(['status' => 2]);
                continue;
            }
            $content = $data[0]['content'];
            $info = Db::name('article')->where(['article_id' => $v['article_id'], 'source' => '金色财经'])->find();
            if ($info) {
                Db::name('collect_article')->where(['id' => $v['id']])->update(['status' => 2]);
                continue;
            }
            $res = Picture::create([
                'sha1' => getRandomStr(10),
                'name' => $v['img'],
                'path' => $v['img'],
                'url' => $v['img'],
            ]);
            \app\common\model\Article::create([
                'name' => $v['title'],
                'describe' => $v['describe'],
                'content' => $content,
                'category_id' => 2,
                'cover_id' => $res->id,
                'is_collect' => 1,
                'member_id' => 1,
                'article_id' => $v['article_id'],
                'source' => '金色财经'
            ]);
            Db::name('collect_article')->where(['id' => $v['id']])->update(['status' => 2]);

        }


    }

    //采集微博内容
    public function weibo_collect()
    {
        include_once(ROOT_PATH . 'extend/QueryList/phpQuery.php');
        include_once(ROOT_PATH . 'extend/QueryList/QueryList.php');
        $html = file_get_contents('https://m.weibo.cn/api/container/getIndex?containerid=100103type%3D1%26q%3D%E5%8C%BA%E5%9D%97%E9%93%BE&page_type=searchall');
        dd(json_decode($html, true));
        $rules = array(
            //采集id为one这个元素里面的纯文本内容
            'title' => array('.js-title', 'title'),
            //采集class为two下面的超链接的链接
            'link' => array('.js-title', 'href'),
            //采集class为two下面的第二张图片的链接
            'img' => array('.js-single__left>img', 'src'),
            //采集span标签中的HTML内容
            'other' => array('.js-single__des', 'text')
        );

        $data = QueryList::Query($html, $rules)->data;
    }


    public function tree()
    {
        set_time_limit(0);
        $list = \app\common\model\Member::all(['path' => 0, 'is_inside' => 0]);

        Db::startTrans();
        foreach ($list as $k => $v) {
            try {
                if ($v->leader_id) {
                    $mem = \app\common\model\Member::get($v->leader_id);
                    $path = $v['id'] . ',' . $mem['path'];
                    $v->path = $path;
                } else {
                    $v->path = $v['id'] . ',';
                }
                $ids = \app\common\model\Member::where(['leader_id' => $v['id']])->column('id');
                if ($ids) {
                    $ids = implode(',', $ids);
                    $v->ceng_member = $ids;
                }
                $v->save();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                echo $e->getMessage();
                die;
            }

        }

    }


    //产品分红
    public function add_bonus()
    {

        $list = GamblerKingInvestmentUser::where(['state' => 3, 'settlement_time' => ['lt', time()]])->select();
//        $list=GamblerKingInvestmentUser::where(['state'=>3])->select();
//        dd($list);
        foreach ($list as $k => $v) {
            Db::startTrans();
            try {
                $info=GamblerKingInvestmentUser::where(['id' => $v['id'],'state'=>1])->lock(true)->find();
                if($info){
                    $info->get_reward();
                }
                // echo 1;die;;
                Db::commit();
                echo 1;
            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollback();
            }


        }


    }

//    public function add_bank(){
//        $bank_list=get_bank();
//
//        $banks=[];
//        if($bank_list){
//            foreach ($bank_list as $k=>$v){
//                $bank=[
//                    'symbol'=>$k,
//                    'name'=>$v,
//                    'logo'=>get_bank_log($k),
//                    'create_time'=>TIME_NOW
//                ];
//                $banks[]=$bank;
//            }
////            dd($banks);
//            Bank::insertall($banks);
//        }
//    }


    public function start_game()
    {
        $list = GamblerKingInvestmentUser::where(['state' => 1, 'expire_time' => ['lt', time()]])->select();

        foreach ($list as $k => $v) {
            Db::startTrans();


            try {

                $info=GamblerKingInvestmentUser::where(['id' => $v['id'],'state'=>1])->lock(true)->find();
                if($info){
                    $info->end_order();
                }
                Db::commit();
                echo 1;
            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollback();
            }
        }

    }

    public function start_game_two()
    {
        $sql = "SELECT * FROM `tp_gambler_king_investment_user` WHERE  `state` = 1  AND `total_money` >=max_money";
        $list = Db::query($sql);
        foreach ($list as $k => $v) {
            Db::startTrans();


            try {
                $info=GamblerKingInvestmentUser::where(['id' => $v['id'],'state'=>1])->lock(true)->find();
                if($info){
                    $info->end_order();
                }
                Db::commit();
                echo 1;
            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollback();
            }
        }

    }

    /***
     * 开始游戏超时
     */
    public function start_expire_game()
    {
        $list = GamblerKingInvestmentUser::where(['state' => 2, 'start_game_end_int' => ['lt', time()]])->select();
        UserKingInvestment::where(['state' => 1, 'create_time' => ['lt', TIME_NOW - 1800]])->update(['state' => 3]);
        foreach ($list as $k => $v) {
            Db::startTrans();


            try {
                $info=GamblerKingInvestmentUser::where(['id' => $v['id'],'state'=>2])->lock(true)->find();
                if($info){
                    $info->start_expire_game();
                }

                Db::commit();
                echo 1;
            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollback();
            }
        }

    }


    //动态奖金奖励
    public function action_reward()
    {


        $list = BonusLog::where(['status' => 1, 'number' => ['gt', 0], 'type' => 2])->select();
        // dd($list);

        foreach ($list as $k => $v) {
            Db::startTrans();
            $info = BonusLog::where(['id' => $v['id']])->lock(true)->find();
            if ($info['status'] == 1) {
                try {
                    $account = UserAccount::check(['user_id' => $v['user_id'], 'wallet_id' => 3], false);
//                    //分享奖
                    //团队奖
                    $account->share_reward($info);
                    $v->status = 2;
                    $v->save();
                    // echo 1;die;
                    Db::commit();
                    echo 1;
                } catch (\Exception $e) {
                    echo $e->getMessage();
                    Db::rollback();
                }
            }


        }
    }


    /**
     * OTC付款超时
     */

    public function otc_expire()
    {
        $date = date('Y-m-d H:i:s');
        $list = OtcOrder::where(['state' => 1, 'pay_expire_time' => ['lt', time()]])->select();

        foreach ($list as $k => $v) {
            Db::startTrans();
            try {
                //取消退回
                if ($v['otc_type'] == 1) {
                    //退币
                    Db::name('transfer')->where(['id' => $v['withdrwal_id']])->setInc('money', $v['total']);
                    Db::name('transfer')->where(['id' => $v['withdrwal_id']])->update(['state' => 7]);

                }
                Db::name('otc_trading')->where(['id' => $v['otc_id']])->setInc('feed_count', 1);
                Db::name('otc_trading')->where(['id' => $v['otc_id']])->setInc('surplus_number', $v['number']);
                Db::name('otc_trading')->where(['id' => $v['otc_id']])->setInc('surplus_total', $v['total']);
                Db::name('otc_trading')->where(['id' => $v['otc_id']])->update(['state' => 0]);
                $v->state = 7;
                $v->feedback_content = '打款超时';
                user_notice($v['user_id'], '您在' . $date . '时间，通过法币交易充值，因未能及时付款，已超时，本次记录您的不良交易记录');
                $v->save();
                Db::commit();
            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollback();
            }
        }


    }


    /**
     * OTC收款超时
     */

    public function otc_revecive_expire()
    {


        $list = OtcOrder::where(['state' => 3, 'receive_expire_time' => ['lt', time()]])->select();
        $arr = $orders = $buy_orders = $bad_records = [];
        $time = TIME_NOW;
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                if ($v['otc_type'] == 1) {

                    //买单自动收款完成
                    $buy_orders[] = $v['id'];

                    //买家余额增加

                    $arr['receive_time'] = $time;


                    $log['remark'] = '店铺代发买入';
                    $v->shop->number_do += $v['number'];
                    $v->shop->number_total += $v['number'];
                    $receive_minute = ceil(($time - $v->getData('pay_time')) / 60);

                    $arr['receive_minute'] = $receive_minute;
                    //更新卖家成交量，发放手续费
                    $v->shop->success_count += 1;
                    if ($v['poundage_number']) {
                        $v->shop->poundage_number += $v['poundage_number'];
                        ShopPoundageLog::create([
                            'user_id' => $v->shop['user_id'],
                            'shop_id' => $v['shop_id'],
                            'order_id' => $v['id'],
                            'otc_id' => $v['otc_id'],
                            'type' => $v['withdrwal_id'] > 0 ? 2 : 1,
                            'number' => $v['poundage_number'],
                            'total' => $v['poundage_number'] * $v['price'],
                        ]);


                    }
                    $v->shop->number_do += $v['poundage_number'];
                    $v->shop->number_total += $v['poundage_number'];
                    $v->shop->turnover += $v['total'];
                    $v->shop->save();
                    Db::name('transfer')->where(['id' => $v['withdrwal_id']])->update(['state' => 1, 'remark' => '放行超时默认自动放行']);
                    user_notice($v['uid'], '您在' . $v->transfer->create_time . '时间操作了一笔提现订单，现由' . $v->shop->shop_name . '商家放行成功，如您没能收到提现款，请前往《法币交易》中进行订单的申诉提交，超时将自动默认为收款成功。');

                } else {
                    //卖单进入申诉订单
                    $data = [
                        'order_id' => $v['id'],
                        'user_id' => $v['user_id'],
                        'content' => '卖家收款超时',
                        'create_time' => TIME_NOW
                    ];
                    $arr[] = $data;
                    $orders[] = $v['id'];
                    //写入不良记录
                    $bad_records[] = [
                        'user_id' => $v['uid'],
                        'remark' => '收款超时',
                        'create_time' => TIME_NOW
                    ];
                    if ($v['otc_type'] == 1) {
                        //修改提现订单状态
                        Db::name('transfer')->where(['id' => $v['withdrwal_id']])->update(['state' => 8]);

                    }

                    if ($v->user->mobile) {
                        //发消息

                        $lang = in_array($v->user->area, ['86', '852', '853', '886']) ? 'zh-hk' : 'en-us';
                        $content = getConfig('otc_revecive_expire_' . $lang);

                        $data = [
                            'mobile' => $v->user->mobile,
                            'content' => $content,
                            'create_time' => TIME_NOW,
                            'sms_type' => 15,
                            'type' => 0,
                            'area' => $v->user->area
                        ];
                        $sms = UserSms::create($data);

                        if (getConfig('sms_is_test') != 1) {
                            $res = send_sms($v->user->mobile, $content, config('settings'), $v->user->area);
                            if ($res) {
                                UserSms::where(['id' => $sms->id])->update(['state' => 2]);
                            }
                        }


                    }
                }


            }
            if (!empty($arr)) {
                OtcFeedback::insertall($arr);
            }
            if (!empty($orders)) {
                OtcOrder::where(['id' => ['in', $orders]])->update(['state' => 8, 'feedback_content' => '收款超时']);
            }
            if (!empty($buy_orders)) {
                OtcOrder::where(['id' => ['in', $buy_orders]])->update(['state' => 2, 'remark' => '收款超时自动收款']);
            }
            if (!empty($bad_records)) {
                UserBadRecord::insertall($bad_records);
            }
            Db::commit();

        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
        }

    }

    /***
     * OTC每月发放利息
     */

    public function copy_shop()
    {
//        if(getConfig('otc_cumulative_money_switch')==0){
//            echo '暂未开启该功能';
//        }
        $shop_list = OtcShop::all(['status' => 1, 'state' => 2]);
        $shoops = [];
        foreach ($shop_list as $k => $v) {
            $shop = [
                'create_time' => time(),
                'shop_id' => $v['id']
            ];
            $shoops[] = $shop;


        }

        Db::startTrans();
        try {
            if ($shoops) {
                Db::name('otc_shop_copy')->insertAll($shoops);
            }

            Db::commit();

        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
        }


    }


    /***
     * OTC每月发放利息
     */

    public function otc_month_interest()
    {

        $shop_list = Db::name('otc_shop_copy')->where(['status' => 1])->select();

        foreach ($shop_list as $k => $v) {
            Db::startTrans();
            try {
                $shop = OtcShop::get($v['shop_id']);
                $shop->interest_reward();
                Db::name('otc_shop_copy')->where(['id' => $v['id']])->delete();
                Db::commit();

            } catch (\Exception $e) {
                echo $e->getMessage();
                Db::rollback();
            }


        }


    }


    /**
     * 获取法币汇率
     */
    public function get_currency_rate()
    {
        $wallet = \app\common\model\Wallet::all(['status' => 1, 'is_virtual' => 0]);
        foreach ($wallet as $k => $v) {
            if ($v['symbol'] != 'CNY') {
//                    $name=strtoupper($v['symbol']);
                $money = convertCurrency($v['symbol'], 'CNY', 1);
                d($money);
                if ($money) {
                    cache('currency_' . $v['symbol'], $money);
                }
                
            }
        }
       
       
    }


    /***
     * 更新法币汇率
     */
    public function update_currency_rate()
    {
        $wallet = \app\common\model\Wallet::all(['status' => 1, 'is_virtual' => 0]);   
        $prices = [];
        foreach ($wallet as $k => $v) {
            if ($v['symbol'] != 'cny') {

                $money = cache('currency_' . $v['symbol']);
                d($money);
                if ($money) {
                    $price = [
                        'symbol' => $v['symbol'],
                        'wallet_id' => $v['id'],
                        'is_virtual' => 0,
                        'price' => $money,
                        'create_time' => TIME_NOW,
                    ];
                    $prices[] = $price;
                    $v->parities = $money;
                    $v->save();
                }
            }
        }
        
        WalletPrice::insertall($prices);
    }



//    /***
//     * 修改直推人
//     */
//    public function update_member(){
//        $list=Member::all(['path'=>['like','%,400,%']]);
//        Db::startTrans();
//        try{
//            $member=Member::get(381);
//            $member1=Member::get(400);
//            foreach ($list as $k=>$v){
//                $path1=substr($v['path'],-13);
//                $arr=[];
//                $path_ids=explode(',',$v['path']);
//                foreach ($path_ids as $ke=>$va){
//                    if($ke>0){
//                        if($va==398){
//                            break;
//                        }
//                    }
//                    $arr[]=$va;
//                }
//                $path2=','.implode(',',$arr);
//                $path=$path2.$path1;
//                $v->path=$path;
//                $v->dai_level-=6;
//                $v->save();
//            }
//            $member->ceng_member='400,'.$member->ceng_member;
//            $member1->leader_id=381;
//            $member1->save();
//            $member->save();
//            Db::commit();
//        }catch (\Exception $e){
//            Db::rollback();
//            echo  $e->getMessage();
//        }
//
//    }


    /***
     * 扣除分红
     */
    public function update_member(){
        $list=BonusLog::where(['user_investment_id'=>35,'type'=>2])->group('user_id')->column('user_id');
        Db::startTrans();
        try{
            foreach ($list as $k=>$v){
                UserAccount::where(['user_id'=>$v,'wallet_id'=>3])->setInc('freeze_balance',1000);
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            echo  $e->getMessage();
        }

    }

    /**
     * 用户商家解封
     */
    public function unsealing()
    {
        Db::name('member')->where(['no_login_time' => ['lt', time()], 'is_login' => 0])->update(['is_login' => 1, 'no_login_time' => 0]);
        Db::name('member')->where(['penalty_time' => ['lt', time()]])->update(['penalty_time' => 0]);

        Db::name('application_user_ticket')->where(['expire_time' => ['lt', time()]])->update(['status' => 2]);

        Db::name('otc_shop')->where(['penalty_time' => ['lt', time()], 'is_release' => 0])->update(['penalty_time' => 0, 'is_release' => 1]);
        Db::name('otc_shop')->where(['no_match_time' => ['lt', time()], 'is_match' => 0])->update(['no_match_time' => 0, 'is_match' => 1]);
    }


    /***
     * 每天统计用户下注输赢金额
     */

    public function add_bets_daily()
    {
        $start_time = getTodayStart() - 86400;
        $end_time = getTodayEnd() - 86400;
        $ids = BetsLog::where(['create_time' => ['between', [$start_time, $end_time]]])->group('user_id')->column('user_id');
        $arrs = [];
        $winner_money = $lose_money = $transfer_count = 0;
        foreach ($ids as $k => $v) {
            $user_lose_money = GamesLog::where(['type' => 4, 'is_winner' => 2, 'user_id' => $v, 'entrust_count' => 0, 'user_investment_id' => 0, 'create_time' => ['between', [$start_time, $end_time]]])->sum('profit') + 0;

            $address = UserAccount::where(['user_id' => $v, 'wallet_id' => 6])->value('blockchain_address2');
            $king_lose_money = Db::name('investment_bet_log')->where(['state' => ['gt', 1], 'profit' => ['lt', 0], 'user_id' => $v, 'create_time' => ['between', [$start_time, $end_time]]])->sum('profit') + 0;
            $winner_money = GamesLog::where(['type' => 4, 'state' => 4, 'is_winner' => 1, 'user_id' => $v, 'create_time' => ['between', [$start_time, $end_time]]])->sum('profit') + Db::name('investment_bet_log')->where(['state' => ['gt', 1], 'profit' => ['gt', 0], 'user_id' => $v, 'create_time' => ['between', [$start_time, $end_time]]])->sum('profit') + 0;;
            if ($winner_money) {
                $arr1 = [
                    'user_id' => $v,
                    'address' => $address,
                    'state' => 1,
                    'number' => $winner_money,
                    'king_lose_number' => 0,
                    'user_lose_number' => 0,
                    'investment_lose_number' => 0,
                    'create_time' => time(),
                    'update_time' => time(),
                    'type' => 2
                ];
                $arrs[] = $arr1;
                $winner_money += $winner_money;
            }
            if ($user_lose_money + $king_lose_money < 0) {
                $arr1 = [
                    'user_id' => $v,
                    'address' => $address,
                    'state' => 1,
                    'number' => $king_lose_money + $user_lose_money,
                    'king_lose_number' => -$king_lose_money,
                    'user_lose_number' => -$user_lose_money,
                    'investment_lose_number' => -$king_lose_money,
                    'create_time' => time(),
                    'update_time' => time(),
                    'type' => 1
                ];
                $lose_money += $arr1['number'];
                $arrs[] = $arr1;
            }
            $transfer_count += 1;


        }
        if ($arrs) {
            Db::name("games_daily_log")->insertAll($arrs);
        }

        $info = ChainDailyStatistics::where(['create_time' => ['between', [getTodayStart() - 86400, getTodayEnd() - 86400]]])->find();
        if ($info) {
            $info->winner_money += $winner_money;
            $info->lose_money -= $lose_money;
            $info->transfer_count += $transfer_count;
            $info->save();

        } else {
            ChainDailyStatistics::create([
                'winner_money' => $winner_money,
                'lose_money' => -$lose_money,
                'transfer_count' => $transfer_count,
                'create_time' => TIME_NOW
            ]);
        }

    }

    /**
     * 未处理每日统计
     */
    public function bet_daily_online()
    {
        $daily_online = Db::name("games_daily_log")->where(['state' => 1])->select();

        $ccie = Db::name("wallet")->where(["id" => 18])->find();
        $url = COIN_URL . "/api/v1/transfer/add";

        foreach ($daily_online as $k => $v) {

            $post_data = array(
                "code" => "ETH/" . strtoupper($ccie['symbol']),
                "to_address" => $v['address'],
                
                "number" => $v['number'],
                
                "nonce_str" => rand(1000, 9999),
                "filter"=>"geth"
            );
            if ($v['type'] == 1) {
                $post_data['from_address'] = $ccie['ccie_bet_address'];
                
            } else {
                $post_data["from_address"] = $ccie["ccie_reward_address"];            
            }
            $password = CoinAddress::where(['address' => $post_data["from_address"]])->value('label');
            
            $post_data['password'] = $password;
            $post_data['contractaddress'] = $ccie['contractaddress'];
            $post_data['private_key'] = '';
            $post_data['gas_limit'] = '';
            $post_data['gas_price'] = '';
            $sign = md5(asc_sort($post_data) . '&key=' . "79ba9e912e708a0a3177df0641be1e5a");
            $post_data['sign'] = $sign;
            

            $dat = json_decode(mycurl($url, $post_data, 1), true);

            if ($dat['status'] == 1) {

                Db::name("games_daily_log")->where(["id" => $v["id"]])->update(["state" => 2, 'hash' => $dat['data']]);
            } else {
                echo $dat['msg'];
                die;
            }


        }
    }

    public function bet_online_test(){


        $ccie = Db::name("wallet")->where(["id" => 18])->find();
        $url = COIN_URL . "/api/v1/transfer/add";


            $post_data = array(
                "code" => "ETH/" . strtoupper($ccie['symbol']),
                "to_address" => "0x6c00a4aed7cf2748bec058873269d7a408a89346",
                
                "number" => 1,
                
                "nonce_str" => rand(1000, 9999),
                "filter"=>"geth"
            );
          
                $post_data['from_address'] = $ccie['ccie_bet_address'];
                
            
            $password = CoinAddress::where(['address' => $post_data["from_address"]])->value('label');
            
            $post_data['password'] = $password;
            $post_data['contractaddress'] = $ccie['contractaddress'];
            $post_data['private_key'] = '';
            $post_data['gas_limit'] = '';
            $post_data['gas_price'] = '';
            $sign = md5(asc_sort($post_data) . '&key=' . "79ba9e912e708a0a3177df0641be1e5a");
            $post_data['sign'] = $sign;
            

            $dat = json_decode(mycurl($url, $post_data, 1), true);
            dump($post_data);
            dump($dat);exit;


    }

    /***
     * 获取线上转账详情
     */

    public function online_detail()
    {
        $list = Db::name('online_transfer')->where(['gas' => ''])->select();
        $url = COIN_URL . "/api/v1/transfer/detail";
        $wallet = \app\common\model\Wallet::get(['id' => 18]);
        $contractaddress = $wallet['contractaddress'];
        foreach ($list as $k => $v) {

            $post_data = array(
                "code" => "ETH/" . strtoupper($wallet['symbol']),
                "contract_address" => $contractaddress,
                "tx_id" => $v['hash'],
                "api_key" => '',
                "nonce_str" => rand(1000, 9999)
            );
            $post_data['filter'] = 'geth';
            $sign = md5(asc_sort($post_data) . '&key=' . "79ba9e912e708a0a3177df0641be1e5a");
            $post_data['sign'] = $sign;
            // dump($post_data);

            $dat = json_decode(mycurl($url, $post_data, 1), true);
            if (!empty($dat['status']) && $dat['status'] == 1) {
                Db::name("online_transfer")->where(["id" => $v["id"]])->update(["gas" => $dat['data']['gasLimit'] * $dat['data']['gasPrice']]);
            }
        }
    }

    /***
     * 获取线上转账详情
     */

    public function games_daily_gas()
    {
        $list = Db::name("games_daily_log")->where(['state' => 2, 'gas' => 0])->select();
        $url = COIN_URL . "/api/v1/transfer/detail";


        foreach ($list as $k => $v) {
            $dat = json_decode(mycurl($url . $v['hash']), true);
            if (!empty($dat['status']) && $dat['status'] == 1) {
                if ($dat['data']['status'] == 1) {
                    Db::name("games_daily_log")->where(["id" => $v["id"]])->update(["gas" => $dat['data']['gasLimit'] * $dat['data']['gasPrice'], 'state' => 3]);
                } else {
                    Db::name("games_daily_log")->where(["id" => $v["id"]])->update(["gas" => $dat['data']['gasLimit'] * $dat['data']['gasPrice']]);
                }

            }
        }
    }


    /**
     * 每天统计用户下注输的金额
     */

    public function add_app_balance()
    {

        $begin_time = getTodayStart() - 86400;

        $end_time = getTodayEnd() - 86400;

        $ids = GamesLog::where(['type' => 4, 'state' => 4, 'is_winner' => 2, 'entrust_count' => 0, 'create_time' => ['between', [$begin_time, $end_time]]])->group('user_id')->column('user_id');
        $users_list = $kings_list = [];
        foreach ($ids as $k => $v) {
            $total = GamesLog::where(['type' => 4, 'user_id' => $v, 'state' => 4, 'entrust_count' => 0, 'create_time' => ['between', [$begin_time, $end_time]]])->sum('profit') + 0;
            $member = Member::get($v);
            if ($member->level_id > 1) {
                $level_time = UserLevelLog::where(['type' => 1, 'user_id' => $v, 'level' => 2])->value('create_time');
                if ($level_time) {
                    $investment = UserKingInvestment::where(['create_time' => ['gt', $level_time], 'user_id' => $v, 'state' => ['in', [0, 4, 5, 6, 7, 8]]])->count();
                    if ($investment == 0) {
                        $loss_bet = $total;
                    } else {
                        $loss_bet = $total * $member->level->lose_return / 100;
                    }
                }

            } else {
                $loss_bet = $total * $member->level->lose_return / 100;
            }
            if ($total < 0) {
                $total = 0 - $loss_bet;
                $users_list[$v] = [
                    'loss_bet' => $total
                ];
            }

        }

        if (!empty($users_list)) {
            $sql4 = updateAllSql("tp_member", key($users_list), $users_list, "id");
            Db::execute($sql4);
        }

    }


    /**
     * 每天更新用户店铺开店时间段更新
     */

    public function user_shop_edit()
    {
        $list = Member::all(['start_time' => ['neq', ''], 'start_time_int' => ['lt', getTodayStart()]]);
        foreach ($list as $k => $v) {
            $v->start_time_int = strtotime(date('Y-m-d') . ' ' . $v['start_time']);
            $v->end_time_int = strtotime(date('Y-m-d') . ' ' . $v['end_time']);
            $v->save();
        }
    }


    /***
     * 测试第三方接口下注
     */
    public function test_bets()
    {
        $url = 'http://bj.testbj.net/api/systemsets/rebaterate/407/3456';
        $time = TIME_NOW;


        $res = mycurl($url, 1);
        $res = json_decode($res, false);
        dd($res);
    }

    public function address_get_private(){
        $url = COIN_URL."/api/v1/address/keystore";
        $address = "f2fd52f4084e30bb23bd73ce248e0de1caa2551a";
        
            $address2 = "0x".$address;
            $password = CoinAddress::where(['address'=>$address2])->value('label');
            $post_data = array(
                "filter"=>"geth",
                "code" => "ETH",
               "address"=>$address,
               "nonce_str" => rand(1000,9999),
                "password" => $password, 
           );
           $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");
           $post_data['sign'] = $sign;
        //    dump($post_data);exit;
           $dat=json_decode(mycurl($url,$post_data,1),true);
           $result["address"] = $address;
           $result["key"] = $dat["data"];
           dump($result);
        
    }

    /***
     * 第三方登录
     */
    public function login()
    {
//        $username='abc002';$pwd='e10adc3949ba59abbe56e057f20f883e';
        $user_arr = [
            'userName' => 'abc002'
        ];
        $time = TIME_NOW;
        $sign = md5($time . json_encode($user_arr) . 'ty25w3f8jkgg1xw633ypkg16');
        $header_sign = $sign . '_' . $time;
        $heades = [
            'X-Signature-Code:' . $header_sign,
        ];
        $res = mycurl('http://www.testbj.net/api/external/balance', json_encode($user_arr), 1, $heades);
        dd(json_decode($res, true));


    }


//    /***
//     * 重写用户地址
//     */
//
//    public function edit_address(){
//        $list=UserAccount::where(['blockchain_address2'=>['neq',''],'wallet_id'=>['in',[6,8]]])->column('user_id');
//        foreach ($list as $k=>$v){
//            $address2=CoinAddress::where(['status'=>0,'mid'=>6,'type'=>0])->order('id asc')->find();
//            if(empty($address2)){
//                echo '地址库不足';exit;
//            }
//            UserAccount::where(['user_id'=>$v,'wallet_id'=>['in',[6,8]]])->update(['blockchain_address2'=>$address2['address'],'blockchain_address'=>$address2['address']]);

//            $res = Db::name("coin_address")->where(["id"=>$address2["id"]])->update(['status'=>1]);
//            if(!$res){
//                echo '状态更新失败';exit;
//            }
//        }
//        echo '完成';exit;
//    }


    /***
     * 15天清算结算
     */
    public function scheduled_liquidation()
    {

        OtcShop::where(['status' => 1])->update(['is_transfer' => 0]);
        $day = date('d');
        $time = TIME_NOW;
        $days_count = date("t");

        if ($day == 1 || $day == 16) {
            $member_list = Member::where(['loss_bet' => ['gt', 0]])->column('id');

            foreach ($member_list as $k => $v) {
                if (cache('scheduled_liquidation_' . $v)) {
                    continue;
                }
                Db::startTrans();
                try {
                    $company = CompanyAccount::get(2);
                    $total = BonusLog::where(['type' => 2, 'user_id' => $v, 'number' => ['gt', 0], 'create_time' => ['between', [TIME_NOW - 15 * 86400, TIME_NOW]]])->sum('number') + 0;

                    $member = Member::get($v);
                    $total = $total * $member->level->lose_return / 100;
                    $money = -$total;
                    $member->loss_bet += $money;
                    $company_account = $company['balance'];
                    if ($company_account == 0) {
                        $member->save();
                        Db::commit();
                        continue;
                    }
                    if ($member->loss_bet > 0) {
                        $money = $member->loss_bet;
                        if ($company_account == 0 || $total == $company_account) {
                            //共生池余额为0，无法释放
                            $money = 0;
                        }

                        if ($money > $company_account) {
                            $new_money = $money;
                            $money = $company_account;
                            $member->loss_bet = $new_money - $money;
                            $member->app_balance += $money;
                            $member->has_lose_bet += $money;

                        } else {
                            $member->loss_bet = 0;
                            $member->app_balance += $money;
                            $member->has_lose_bet += $money;
                        }


                        if ($money > 0) {
                            $user_account = [
                                'user_id' => $v['id'],
                                'type' => 1,
                                'king_id' => 0,
                                'is_add' => 1,
                                'remark' => '15天亏损金额释放',
                                'create_time' => $time,
                                'serial_number' => 'AP' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                                'number' => $money
                            ];
                            AppAccountLog::create($user_account);
                            $bonus_log = [
                                'user_id' => $v,
                                'type' => 3,
                                'number' => $money,
                                'remark' => '15天亏损金额全部释放',
                                'create_time' => TIME_NOW,
                                'serial_number' => 'UO' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(1000, 9999),
                            ];
                            BonusLog::create($bonus_log);
                            $company->balance -= $money;
                            //写入共生池支出流水
                            CompanyAccountLog::create([
                                'user_id' => 2,
                                'type' => 3,
                                'number' => $money,
                                'remark' => '共生池支出',
                            ]);


                        }


                    }
                    //总流水的0.001发放奖励

                    $total += Db::name('investment_bet_log')->where(['state' => ['gt', 1], 'user_id' => $v, 'create_time' => ['between', [getTodayStart() - 86400 * 15, getTodayEnd() - 86400 * 15]]])->sum('number') + 0;
                    $total += BetsLog::where(['create_time' => ['between', [getTodayStart() - 86400 * 15, getTodayEnd() - 86400 * 15]], 'entrust_count' => 0, 'user_id' => $v])->sum('money');
                    if ($total > 0) {
                        $log_money = format_money($total * 0.001, 2);
                        if ($log_money >= 0.01 && $company->balance > 0) {
                            if ($log_money > $company->balance) {
                                $log_money = $company->balance;
                                $company->balance = 0;
                                //写入共生池支出流水
                                CompanyAccountLog::create([
                                    'user_id' => 2,
                                    'type' => 3,
                                    'number' => $money,
                                    'remark' => '共生池支出',
                                ]);
                            } else {
                                $company->balance -= $log_money;
                                //写入共生池支出流水
                                CompanyAccountLog::create([
                                    'user_id' => 2,
                                    'type' => 3,
                                    'number' => $log_money,
                                    'remark' => '共生池支出',
                                ]);
                            }
                            $member->app_balance += $log_money;
                            $user_account = [
                                'user_id' => $v['id'],
                                'type' => 1,
                                'king_id' => 0,
                                'is_add' => 1,
                                'remark' => '15天游戏流水金额的0.001比例释放',
                                'create_time' => $time,
                                'serial_number' => 'AP' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                                'number' => $log_money
                            ];
                            AppAccountLog::create($user_account);
                            $bonus_log = [
                                'user_id' => $v,
                                'type' => 3,
                                'number' => $log_money,
                                'remark' => '15天游戏流水金额的0.001比例释放',
                                'create_time' => TIME_NOW,
                                'serial_number' => 'UO' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(1000, 9999),
                            ];
                            BonusLog::create($bonus_log);
                        }

                    }


                    $company->save();
                    $member->save();
                    Db::commit();
                    cache('scheduled_liquidation_' . $v, 111, 86400 * 14);
                } catch (\Exception $e) {
                    Db::rollback();
                    echo $e->getMessage();
                }


            }


        }
    }

    /***
     * 每三天考核等级
     */
    public function scheduled_liquidation_achievement()
    {

        $member_list = Member::where(['level_id' =>['gt',2]])->column('id');
        Db::startTrans();
        try {
            $member = new Member();
            $member->downgrade_level($member_list);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage() . '</br>';
        }


    }

    /***
     * 会员每日下注流水返点
     */
    public function daily_return_point()
    {

        $level_ids = UserLevel::where(['status' => 1, 'contribution_reward' => ['gt', 0]])->column('id');

        $user_id1s = BetsLog::where(['create_time' => ['between', [getTodayStart() - 86400, getTodayEnd() - 86400]]])->group('user_id')->column('user_id');

        $userid2s = Db::name('investment_bet_log')->where(['create_time' => ['between', [getTodayStart() - 86400, getTodayEnd() - 86400]]])->group('user_id')->column('user_id');
        $userids = array_unique(array_merge($user_id1s, $userid2s));
        $level_list = UserLevel::all(['status' => 1]);
        if (!$level_ids || !$userids) {
            echo '无数据可操作';
        }
        $list = Member::where(['status' => 1])->column('level_id', 'id');
        $new_level = $new_user_account = [];
        foreach ($level_list as $k => $v) {
            $new_level[$v['id']] = $v;
        }

        $user_account = UserAccount::all(['user_id' => ['in', $userids], 'wallet_id' => 1]);
        foreach ($user_account as $k => $v) {
            $new_user_account[$v['user_id']] = $v;
        }
        $accounts = $user_balances = [];
        foreach ($userids as $k => $v) {

            if (!empty($list[$v]) && in_array($list[$v], $level_ids)) {
                $total = 0;
                $total += Db::name('investment_bet_log')->where(['state' => ['gt', 1], 'user_id' => $v, 'create_time' => ['between', [getTodayStart() - 86400, TIME_NOW]]])->sum('number') + 0;

                $total += BetsLog::where(['create_time' => ['between', [getTodayStart() - 86400, getTodayEnd() - 86400]], 'entrust_count' => 0, 'user_id' => $v])->sum('money');
                if ($total > 0) {
                    $reward = $total * $new_level[$list[$v]]['contribution_reward'] / 100;
                    if ($reward >= 0.01) {
                        $user_balances[$new_user_account[$v]['id']] = [
                            'balance' => $reward
                        ];
                        $new_user_account[$v]->balance += $reward;
                        $account_log = [
                            'user_id' => $v,
                            'number' => $reward,
                            'wallet_id' => 1,
                            'before_blance' => $new_user_account[$v]->balance - $reward,
                            'after_blance' => $new_user_account[$v]->balance,
                            'is_add' => 1,
                            'type' => 4,
                            'create_time' => TIME_NOW,
                            'serial_number' => date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                            'is_reward' => 1,
                            'remark' => '每日流水贡献奖励',
                        ];

                        $accounts[] = $account_log;
                    } else {
                        user_notice($v, '您的流水贡献奖励，因低于0.01元，无法为您发放，请知悉本系统作为通知告知委托人');
                    }
                }
            }
        }
        Db::startTrans();
        try {
            if (!empty($user_balances)) {
                $sql4 = updateAllSql("tp_user_account", key($user_balances), $user_balances, "id");
                Db::execute($sql4);
            }
            if (!empty($accounts)) {
                UserAccountLog::insertall($accounts);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage() . '</br>';
        }

    }


    /***
     * 会员挖矿每日释放
     */
    public function daily_mine_release()
    {


        $list = Db::name('dig_click')->where(['state' => 0,'status'=>1,'surplus_number'=>['gt',0]])->select();
        if (!$list ) {
            echo '无数据可操作';
        }
        $accounts = $user_balances =$dig_clicks=$bonus_logs= [];
        foreach ($list as $k => $v) {
                if($v['has_day']==14){
                    $number=$v['surplus_number'];
                    $state=1;
                }else{
                    $number=$v['average_number'];
                    if($number==$v['number']){
                        $state=1;
                    }else{
                        $state=0;
                    }

                }
                $dig_clicks[ $v['id'] ]=[
                    'has_day'=>1,
                    'surplus_number'=>-$number,
                    'state'=>$state,
                ];

                if(!empty($user_balances[ $v['user_id'] ])){
                    $user_balances[ $v['user_id'] ]['app_balance']+=$number;
                }else{
                    $user_balances[ $v['user_id'] ]=[
                        'app_balance'=>$number
                    ];
                }

                $user_account = [
                    'user_id' => $v['user_id'],
                    'type' => 1,
                    'king_id' => 0,
                    'is_add' => 1,
                    'remark' => '挖矿每日释放',
                    'number' => $number,
                    'create_time'=>TIME_NOW
                ];
                $accounts[]=$user_account;
                $bonus_log = [
                    'user_id' => $v['user_id'],
                    'type' => 3,
                    'number' =>$number,
                    'remark' => '挖矿每日释放',
                    'create_time'=>TIME_NOW
                ];
                $bonus_logs[]=$bonus_log;
//


        }
        Db::startTrans();
        try {
            if (!empty($user_balances)) {
                $sql4 = updateAllSql("tp_member", key($user_balances), $user_balances, "id");
                Db::execute($sql4);
                $sql5 = updateAllSql("tp_dig_click", key($dig_clicks), $dig_clicks, "id");
                Db::execute($sql5);
                AppAccountLog::insertAll($accounts);
                BonusLog::insertAll($bonus_logs);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo $e->getMessage() . '</br>';
        }

    }


    /***
     * 定时清理一个月以前的数据
     */

    public function clear_data()
    {
        $time1 = strtotime('-1 month');
//        BetsLog::where(['create_time'=>['lt',$time1]])->delete();
//        BetsLogSubscribe::where(['create_time'=>['lt',$time1]])->delete();
//        BonusLog::where(['create_time'=>['lt',$time1]])->delete();
        LoginLog::where(['create_time' => ['lt', $time1]])->delete();
        LoginLog::where(['create_time' => ['lt', $time1]])->delete();

    }

    /**
     * 定时更新赌王产品时间
     */

    public function edit_investment_time()
    {
        PlanUserProgramme::where(['is_stop_time' => 1, 'end_time' => ['lt', TIME_NOW]])->update(['state' => 4, 'has_end_time' => TIME_NOW]);
        $sql = "UPDATE `tp_plan_user_programme` set state=4  ,  has_end_time=" . TIME_NOW . " WHERE  (`state` = 1  AND  is_stop_win=1  AND `current_win_money` >=stop_win_money) or (`state` = 1  AND  is_stop_lose=1  AND `current_lose_money` >=stop_lose_money) ";
        Db::execute($sql);
        PlanNumber::where(['end_time' => ['lt', TIME_NOW - 3600], 'state' => 1])->update(['state' => 3]);
        $list = GamblerKingInvestment::where(['start_game_int' => ['lt', TIME_NOW]])->select();
        foreach ($list as $k => $v) {
            $v->start_time_int = $v['end_time_int'];

            $v->start_game_int = $v->start_time_int + 86400 * $v['cycle'];
            $v->start_game_end_int = $v->start_game_int + $v['receipt_minute'] * 60;
            $v->end_time_int = $v->start_game_int + 86400 * $v['start_game_time'];
            $v->save();
        }
    }

    /**
     * 第三方订单支付超时
     */
    public function third_application_pay_outtime()
    {
        Db::startTrans();
        try {
            Db::name("hotel_application_order")->where(["status" => 1, "cancel_time" => ["lt", time()]])->update(["status" => -1]);
            Db::name("flight_application_order")->where(["status" => 1, "cancel_time" => ["lt", time()]])->update(["status" => -1]);
            Db::name("train_application_order")->where(["status" => 1, "cancel_time" => ["lt", time()]])->update(["status" => -1]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    //酒店订单状态查询
    public function hotel_order_status_query()
    {
        $api_key = getConfig("hotel_train_flight_api_key");
        $api_secret = getConfig("hotel_train_flight_api_secret");
        $api_url = getConfig("hotel_train_flight_api_url");
        $list = Db::name("hotel_application_order")->field("order_no")->where(["status" => 3])->select();
        foreach ($list as $k => $v) {
            $data = array(
                "OrderID" => $v["order_no"],
            );
            $format_data = api_format_data($api_key, $api_secret, $data);
            $heades = [
                'Content-Type:application/json; charset=utf-8',
            ];
            $res = mycurl($api_url . "/Hotel/OrderDetail", $format_data, 1, $heades);
            $result = json_decode($res, true);
            Db::name("hotel_application_order")->update(["order_status" => $result['Data']['OrderStatus']]);
        }
    }

    //火车订单查询
    public function train_order_status_query()
    {
        $api_key = getConfig("hotel_train_flight_api_key");
        $api_secret = getConfig("hotel_train_flight_api_secret");
        $api_url = getConfig("hotel_train_flight_api_url");
        $list = Db::name("train_application_order")->field("order_no")->where(["status" => 3])->select();
        foreach ($list as $k => $v) {
            $data = array(
                "OrderNo" => $v["order_no"],
            );
            $format_data = api_format_data($api_key, $api_secret, $data);
            $heades = [
                'Content-Type:application/json; charset=utf-8',
            ];
            $res = mycurl($api_url . "/Train/QueryOrderDetail", $format_data, 1, $heades);
            $result = json_decode($res, true);
            Db::name("train_application_order")->update(["order_status" => $result['Data']['OrderInfo']['OrderStatus']]);
        }
    }

    //滴滴--回调
    public function didi_return()
    {
        $request = file_get_contents('php://input');
        $request_arr = json_decode($request, true)['data'];
        $order_number = $request_arr['sn'];
        $result = Db::name("didi_application_order")->where(["order_number" => $order_number])->find();

        $user_id = $result['user_id'];
        if (empty($result)) {
            echo json_encode(ajaxreturn(1, "订单不存在"));
            exit;
        }

        $status = $request_arr['status'];
        Db::startTrans();
        try {
            if ($status == 'dispatched' || $status == 'arriving') {
                //已派单添加司机信息
                //高德api计算司机距离与预计时间
                $url = 'https://restapi.amap.com/v3/distance?origins=' . $request_arr['driverLng'] . ',' . $request_arr['driverLat'] . '&destination=' . $result['slng'] . ',' . $result['slat'] . '&output=json&type=1&key=01aa604cfc29dc198a5ec3b52b7a9b7a';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
                $distance_result = curl_exec($ch);
                $distance_result = json_decode($distance_result, true);
                // dump($distance_result);exit;
                curl_close($ch);
                $data = array(
                    'driver_name' => $request_arr['driverName'],
                    'driver_license' => $request_arr['driverVehicleNo'],
                    'driver_score' => $request_arr['driverScore'],
                    'driver_lat' => $request_arr['driverLat'],
                    'driver_lng' => $request_arr['driverLng'],
                    'driver_vehicle_model' => $request_arr['driverVehicleModel'],
                    'driver_mobile' => $request_arr['driverVirtualPhone4Purchaser'],
                    // 'driver_virtual_phone4_passenger' => $request_arr['driverVirtualPhone4Passenger'],
                    'status' => $request_arr['status'],
                    'driver_distance' => $distance_result['results'][0]['distance'],
                    'driver_arrive_time' => $distance_result['results'][0]['duration']
                );
                //短信记录
//                if(M("taxi_message")->where(['order_num'=>$order_number,'type'=>'arriving'])->count()==0){
//                    //action('api/api/sms', ['phone' => $result['mobile'],"code"=>"","content" => "【{webname}】您的出行订单已匹配，请在上车地点等候司机到达！"]);
//                }
//                $message = array(
//                    'type' => 'arriving',
//                    "order_num" => $order_number,
//                    'content' => "【{webname}】您的出行订单已匹配，请在上车地点等候司机到达！",
//                    'add_time' => time(),
//                );
//                M('taxi_message')->add($message);
            } else if ($status == 'arrived') {
                $data = array(
                    'driver_lat' => $request_arr['driverLat'],
                    'driver_lng' => $request_arr['driverLng'],
                    'status' => $request_arr['status']
                );
                //短信记录
//                if(M("taxi_message")->where(['order_num'=>$order_number,'type'=>'arrived'])->count()==0){
//                    //action('api/api/sms', ['phone' => $result['mobile'],"code"=>"","content" => "【{webname}】您的出行订单，司机已到达上车地点！"]);
//                }
//                $message = array(
//                    'type' => 'arrived',
//                    "order_num" => $order_number,
//                    'content' => "【{webname}】您的出行订单，司机已到达上车地点！",
//                    'add_time' => time(),
//                );
//                M('taxi_message')->add($message);
            } else if ($status == 'serviceFinished') {
                //结束行程金额变化
                $user_money = Db::name('member')->where(['id' => $user_id])->find()["app_balance"];
                if ($user_money <= $result['price']) {
                    Db::name('taxi_ensure')->where(['userid' => $user_id])->setDec('number', $result['price']);
                } else {
                    Db::name('member')->where(['id' => $user_id])->setDec('app_balance', $result['price']);
                }
                //财务记录
                $log = array(
                    "user_id" => $user_id,
                    "type" => 7,
                    'is_add' => 2,
                    'create_time' => time(),
                    'update_time' => time(),
                    'status' => 1,
                    'serial_number' => $result['order_number'],
                    'number' => $result['price']
                );
                Db::name('app_account_log')->insert($log);
                BonusLog::create([
                    "user_id" => $user_id,
                    "type" => 4,
                    'number' => $result['price']
                ]);

                $data = array(
                    'driver_lat' => $request_arr['driverLat'],
                    'driver_lng' => $request_arr['driverLng'],
                    'status' => 'paid'
                );
            } else if ($status == "invalid" || $status == "completed" || $status == "canceled") {
                $data = array(
                    'status' => $status
                );
            } else {
                $data = array(
                    'driver_lat' => $request_arr['driverLat'],
                    'driver_lng' => $request_arr['driverLng'],
                    'status' => $request_arr['status']
                );
            }

            Db::name('didi_application_order')->where(["order_number" => $order_number])->update($data);
            Db::commit();
            echo 'success';
            exit;
        } catch (\Exception $e) {
            Db::rollback();
            echo 'fail' . $e->getMessage();
            exit;
        }

    }

    function auto_address_transfer(){
        $lists = Db::name("user_address_transfer")->where(["status"=>0])->limit(20);
        $url = COIN_URL."/api/v1/transfer/add";
        foreach($lists as $value){
            $wallet = Db::name("wallet")->where(["id"=>$value["wallet_id"]])->find();
            if($value["type"]==1){
                $password = CoinAddress::where(['address'=>$value["from"]])->value('label');
                $contractaddress = $wallet['contractaddress'];
                $host = $wallet['rpc_host'];
                $post_data = array(
                    "filter"=>"geth",
                    "code" => "ETH",
                   "from_address" => $value['from_address'],
                   "to_address" => $value['to_address'],
                   "number" => $value['number'],
                   "password" => $password,
                   "nonce_str" => rand(1000,9999)
              );
                $post_data['contractaddress'] = $contractaddress;
                $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");
                $post_data['sign'] = $sign; 
                $dat=json_decode(mycurl($url,$post_data,1),true);
                if($dat['msg']=="转账失败：insufficient funds for gas * price + value"){
                    return ['code'=>0,'msg'=>'余额不足'];
                }
                if($dat['status']==1){
                    Db::name("user_address_transfer")->where(["id"=>$value["id"]])->update(["status"=>1]);
                }else{
                    Db::name("user_address_transfer")->where(["id"=>$value["id"]])->update(["status"=>2]);
                }
                    
            }else{
                 $password = CoinAddress::where(['address'=>$value['from']])->value('label');
                $contractaddress = $wallet['contractaddress'];
                $post_data = array(
                    "code" => "ETH",
                   "from_address" => $value['from_address'],
                   "to_address" => $value['to_address'],
                   "number" => $value['number'],
                   "password" => $password,
                   "nonce_str" => rand(1000,9999)
              );
                $post_data['contract_address'] = $contractaddress;
                $post_data['private_key'] = '';
                $post_data['gas_limit'] = '';
                $post_data['gas_price'] = '';
                $sign = md5(asc_sort($post_data).'&key='."79ba9e912e708a0a3177df0641be1e5a");
                $post_data['sign'] = $sign;


                $dat=json_decode(mycurl($url,$post_data,1),true);
                if($dat['status']==1){
                    Db::name("user_address_transfer")->where(["id"=>$value["id"]])->update(["status"=>1]);
                }else{
                    Db::name("user_address_transfer")->where(["id"=>$value["id"]])->update(["status"=>2]);
                }
            }
        }
    }

    function ay_auto_bets(){
        $process = Db::name("auto_bets_process")->where(["status"=>0])->select();
        foreach ($process as $k=>$v){
            $play_user = json_decode($v["play_users"]);
            $wait_users = json_decode($v["wait_users"]);
            $play=LotteryPlay::get($v['play_id']);
            if(!$play){
                return ajaxreturn(1,lang('玩法错误'));
            }
            $lottery=Lottery::get($v['lottery_id']);
            if(!$lottery){
                return ajaxreturn(1,lang('彩种错误'));
            }
            $lottery_info=LotteryRound::get(['lottery_id'=>$v['lottery_id'],'round'=>$v['round']]);
            if(count($play_user)<2){
                $play_user[] = $wait_users[0];
            }
            $codes=['01','02','03','04','05','06','07','08','09','10'];
            for($i=0;$i<5;$i++){
                $len=count($codes);
                $parameter_a[]=$codes[rand(0,$len)];
            }
            $parameter_b = $codes;
            try{
                //A用户投注
                $data['user_id']=$play_user[0];
                $res1=$play->new_add_lottery($data);
                if($res1['status']==1){
                    Db::rollback() ;
                    return ajaxreturn(1,lang($res['msg']));
                }
                $data['user_id']=$play_user[1];
                $res1=$play->new_add_lottery($data);
                if($res2['status']==1){
                    Db::rollback() ;
                    return ajaxreturn(1,lang($res['msg']));
                }
                Db::commit();
                return ajaxreturn(0,lang($res['msg']));
            }catch (\Exception $e){
                Db::rollback();
                return ajaxreturn(1,$e->getMessage());
            }
            //B用户投注

        }
    }


}
